﻿using Seagull.BarTender.Print;
using Seagull.BarTender.Print.Database;
using System;
using System.Drawing.Printing;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.NetworkInformation;
using System.ServiceProcess;
using System.Timers;

namespace PrintService
{

    public partial class PrintService : ServiceBase
    {

        #region fields

        private Timer cleanExpiredFilesTimer = null;
        FileSystemWatcher watcher = null;
        private PrintDocument pd = new PrintDocument();
        HttpServer httpServer = null;

        #endregion

        #region constructors

        public PrintService()
        {
            InitializeComponent();
            this.ServiceName = "Erp Print Service";
            PrintHelper.DefaultPrinter = GetAvailablePrinter();
            LogHelper.LogInfo(string.IsNullOrEmpty(PrintHelper.DefaultPrinter) ? "Please install a useful printer." : string.Format("The printer is {0}", PrintHelper.DefaultPrinter));
        }

        #endregion


        protected override void OnStart(string[] args)
        {
            if (!Directory.Exists(ServiceConstants.DataFolder))
                Directory.CreateDirectory(ServiceConstants.DataFolder);

            if (cleanExpiredFilesTimer == null)
                cleanExpiredFilesTimer = new Timer();

            cleanExpiredFilesTimer.Enabled = true;
            cleanExpiredFilesTimer.AutoReset = true;
            cleanExpiredFilesTimer.Elapsed += cleanExpiredFilesTimer_Elapsed;

            cleanExpiredFilesTimer.Interval = ServiceConstants.CleanExpiredFilesInterval;
            cleanExpiredFilesTimer.Start();

            //每次启动时，手动触发一次时间
            cleanExpiredFilesTimer_Elapsed(new object(), null);

            httpServer = new WriteFileHttpServer(ServiceConstants.ListenPort);
            System.Threading.Thread thread = new System.Threading.Thread(new System.Threading.ThreadStart(httpServer.listen));
            thread.Start();
        }

        protected override void OnStop()
        {
            if (watcher != null)
            {
                watcher.Dispose();
            }

            if (cleanExpiredFilesTimer != null)
            {
                cleanExpiredFilesTimer.Close();
                cleanExpiredFilesTimer.Dispose();
            }

            if (httpServer != null) {
                httpServer.Close();
            }
        }
        private bool PortInUse(int port)
        {
            bool inUse = false;
            IPGlobalProperties ipProperties = IPGlobalProperties.GetIPGlobalProperties();
            IPEndPoint[] ipEndPoints = ipProperties.GetActiveTcpListeners();

            foreach (IPEndPoint endPoint in ipEndPoints)
            {
                if (endPoint.Port == port)
                {
                    inUse = true;
                    break;
                }
            }
            return inUse;
        }

        /// <summary>
        /// 清除过期文件，存放时间超过七天，视为过期
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void cleanExpiredFilesTimer_Elapsed(object sender, ElapsedEventArgs e)
        {
            try
            {
                CleanExpiredFiles();
            }
            catch (Exception ex)
            {
                LogHelper.LogError(string.Format("Error occurred when delete useless file. Error: {0}", ex.Message));
                cleanExpiredFilesTimer.Stop();
                cleanExpiredFilesTimer.Interval = ServiceConstants.CleanExpiredFilesInterval;
                cleanExpiredFilesTimer.Start();
            }
        }

        private void CleanExpiredFiles()
        {
            LogHelper.LogInfo("Start to clean expired files.");
            var directInfo = new DirectoryInfo(ServiceConstants.DataFolder);
            var expireDate = DateTime.Now.AddDays(0 - ServiceConstants.MaintainFileTime).Date;
            foreach (FileInfo fileInfo in directInfo.GetFiles())
            {
                if (fileInfo.CreationTime < expireDate)
                {
                    File.Delete(fileInfo.FullName);
                }
            }
            LogHelper.LogInfo("Clean expired files completed.");
        }

        private string GetAvailablePrinter()
        {
            string availPrinter = string.Empty;
            var availablePrinterBrands = ServiceConstants.PrinterBrands.Split(",".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
            foreach (string installedPrinter in PrinterSettings.InstalledPrinters)
            {
                if (availablePrinterBrands.Any(a => installedPrinter.Contains(a)) && PrintHelper.TestPrint(installedPrinter))
                {
                    availPrinter = installedPrinter;
                    break;
                }
            }
            return availPrinter;
        }
    }
}
